package com.hqq.rabbitmq.publisher;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 基本类型消息的发送器
 * @author huangqiqin
 * @date 2021/04/13 01:22
 **/

@Component
public class BasicMessagePublisher {

    private static final Logger log = LoggerFactory.getLogger(BasicMessagePublisher.class);

    /**
     * 注入JSON序列化对象
     */
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 注入RabbitMQ模板对象
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 注入properties配置文件变量
     */
    @Autowired
    private Environment env;

    /**
     * 发送消息到RabbitMQ
     * @param message
     */
    public void sendMessage(String message){
        try {
            if (!StringUtils.isEmpty(message)){
                // 设置消息传输格式为Json
                //this.rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter(objectMapper));
                // 指定消息发送的交换机
                this.rabbitTemplate.setExchange(env.getProperty("mq.basic.exchange.name"));
                // 指定消息发送的路由key
                this.rabbitTemplate.setRoutingKey(env.getProperty("mq.basic.routing.key.name"));

                // 将字符串转为Message对象
                Message msg = MessageBuilder.withBody(message.getBytes("utf-8")).build();
                // 转换消息格式并发送
                //this.rabbitTemplate.convertAndSend(msg);
                this.rabbitTemplate.send(msg);

                log.info("==> 已发送消息到RabbitMQ，消息内容：{}", msg);
            }
        } catch (Exception e){
            log.error("发送消息到RabbitMQ失败", e);
        }

    }

}
